import axios from "axios";
import { Message } from "element-ui";
import router from '@/router';

let requestFailNum = 0 // 计算状态 403 数量

const service = axios.create({
  baseURL: "/api/v1",
  timeout: 500000,
});

service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    if (requestFailNum > 0) requestFailNum = 0
    return response;
  },
  (error) => {
    if (error.response.status === 403) {
      if (requestFailNum < 1) {
        console.log('第一次403', requestFailNum)
        Message.error("登录过期，请重新登录");
        localStorage.clear();
        router.push("/login");
        requestFailNum = requestFailNum + 1;
        return;
      } else {
        console.log('多次403', requestFailNum)
        return Promise.reject(error);
      }
      
    } else {
      Message.error(error.message);
    }
    return Promise.reject(error);
  }
);

export default service;
